use std::{fs::File, io::BufWriter, path::Path, thread::sleep, time::Duration};

use idgen::IDGen;
use image::{codecs::png::PngEncoder, ColorType, ImageBuffer, ImageEncoder, Rgba};
use tauri::{Manager, Runtime};
use tauri_plugin_clipboard_manager::ClipboardExt;

use crate::{
    APP_DIR, PHYSIZE, dao::config, utils::{cache_util, date_util::get_ym_str, file_util::ensure_parent_dir_exists, response::R}
};

#[tauri::command]
pub fn open_editor_momento(
    handle: tauri::AppHandle,
    win_key: String,
    title: String,
    path: String,
) -> R<bool> {
    println!("打开窗口 {}", win_key);
    open_window(&handle, win_key, title, path);
    R::success()
}

#[tauri::command]
pub fn get_cache_str(key: String) -> Option<String> {
    cache_util::get_cache(&key)
}

#[tauri::command]
pub fn save_clipboard_img(app: tauri::AppHandle) -> Option<String> {
    if let Ok(img) = app.clipboard().read_image() {
        log::info!("1");
        let mut raw: Vec<u8> = img.rgba().to_vec();
        let width = img.width();
        let height = img.height();
        // 强制 alpha 通道为 255（不透明）
        for i in (0..raw.len()).step_by(4) {
            raw[i + 3] = 255;
        }
        // 创建 ImageBuffer
        let buffer: ImageBuffer<Rgba<u8>, Vec<u8>> = match ImageBuffer::from_raw(width, height, raw)
        {
            Some(buf) => buf,
            None => {
                return None;
            }
        };
        log::info!("2");
        let idgen = IDGen::new(1);
        let id = idgen.new_id();
        // 保存路径
        let dic_path;
        match config::get_dic_path_tokio() {
            Some(path) => {
                dic_path = path;
            },
            None => {
                dic_path = APP_DIR.get().unwrap().to_string();
                config::up_dir_config_tokio(dic_path.clone());
            },
        }
        let file_path = Path::new( &(dic_path + "/temp/"))
            .join(get_ym_str())
            .join(id.to_string() + ".png");
        let path = file_path.to_str().unwrap().to_string();
        let _ = ensure_parent_dir_exists(&path);
        log::info!("暂存文件 {}", file_path.to_str().unwrap().to_string());
        // 写入文件
        let file =
            File::create(&file_path).map_err(|e| log::info!("{}", format!("创建文件失败: {}", e)));
        match file {
            Ok(file) => {
                log::info!("3");
                let writer = BufWriter::new(file);
                let encoder = PngEncoder::new(writer);
                // 这里由 encode 改为 write_image
                let result =
                    encoder.write_image(buffer.as_raw(), width, height, ColorType::Rgba8.into());
                match result {
                    Ok(_) => {
                        return Some(path);
                    }
                    Err(_) => {
                        return None;
                    }
                }
            }
            Err(_) => {
                return None;
            }
        }
    }
    None
}

pub fn open_window<R: Runtime>(
    handle: &tauri::AppHandle<R>,
    win_key: String,
    title: String,
    path: String,
) {
    println!("打开窗口 {}", win_key);
    if let Some(win) = handle.get_webview_window(&win_key) {
        let _ = win.show();
        let _ = win.set_always_on_top(true);
        let _ = win.set_focus();
        sleep(Duration::from_millis(100));
        let _ = win.set_always_on_top(false);
        println!("窗口已启动!");
    } else {
        let physize = PHYSIZE.get().expect("Error get pool from OneCell<Pool>");
        let width = physize.get("width").unwrap_or(&(1920 as u32)).clone() as f64;
        let height = physize.get("height").unwrap_or(&(1080 as u32)).clone() as f64;
        //println!("Screen resolution: {}x{}", width, height);
        let w = 960.0;
        let h = 720.0;
        let position_x = width / 2.0 - w / 2.0;
        let position_y = height / 2.0 - h / 2.0;
        println!("Screen resolution: {} x {}", position_x, position_y);
        // 1+1等于多少
        let docs_window = tauri::WebviewWindowBuilder::new(
            handle,
            win_key, /* the unique window label */
            tauri::WebviewUrl::App(path.parse().unwrap()),
        )
        .title(title)
        .inner_size(w, h)
        .position(position_x, position_y)
        .visible(false)
        .build();
        println!("打开窗口2");
        match docs_window {
            Ok(_win) => {
                println!("打开窗口3");
            }
            Err(_) => {
                println!("启动窗口失败!");
            }
        }
    }
}
